package com.gyp.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.http.*;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.ByteArrayInputStream;

public class HttpUtils {

    public static Boolean isHttp(String data) {
        return StringUtils.startsWithAny(data, "http", "https");
    }

    public static String urlToBase64(String url) {

        UrlBuilder urlBuilder = UrlBuilder
                .ofHttp(url, null);
        HttpRequest httpRequest = new HttpRequest(urlBuilder);
        HttpResponse response = httpRequest.timeout(-1)
                .executeAsync();

        byte[] bytes = response.bodyBytes();
        String base64Encoded = Base64.encode(bytes);
        return base64Encoded;
    }

    public static String urlToBase64WithPrefix(String url) {

        UrlBuilder urlBuilder = UrlBuilder
                .ofHttp(url, null);
        HttpRequest httpRequest = new HttpRequest(urlBuilder);
        HttpResponse response = httpRequest.timeout(-1)
                .executeAsync();

        byte[] bytes = response.bodyBytes();
        String prefix = identifyImageFormat(bytes);
        String base64Encoded = Base64.encode(bytes);
        String format = "data:image/%s;base64,%s";
        String base64 = String.format(format, prefix.toLowerCase(), base64Encoded);
        return base64;
    }


    public static String identifyImageFormat(byte[] imageData) {
        try {
            // 创建 ImageInputStream 以读取字节数组
            ImageInputStream imageInputStream = ImageIO.createImageInputStream(new ByteArrayInputStream(imageData));

            // 获取第一个可用的 ImageReader
            ImageReader imageReader = ImageIO.getImageReaders(imageInputStream).next();

            // 获取图像格式名称
            String format = imageReader.getFormatName();

            // 关闭 ImageInputStream
            imageInputStream.close();

            return format;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static byte[] requestDownload(String url){

        UrlBuilder urlBuilder = UrlBuilder
                .ofHttp(url, null);
        HttpRequest httpRequest = new HttpRequest(urlBuilder);
        HttpResponse response = httpRequest.method(Method.GET)
                .setFollowRedirects(true)
                .timeout(-1)
                .executeAsync();

        if (response.isOk()) {
            return response.bodyBytes();
        }
        throw new HttpException("Server response error with status code: [{}]", response.getStatus());
    }


}
